class Snake {
    element: HTMLElement // 蛇的容器
    head: HTMLElement // 蛇头元素
    snakeBody: HTMLCollection // 蛇身体元素

    constructor() {
        this.element = document.getElementById('snake')!;
        this.head = document.querySelector('#snake > div') as HTMLElement;
        this.snakeBody = this.element.getElementsByTagName('div');
    }

    // 获取蛇头坐标
    get X() {
        return this.head.offsetLeft
    }

    get Y() {
        return this.head.offsetTop
    }

    // 设置蛇头坐标
    set X(value){
        if(this.X === value) {
            return
        }
        if(this.X < 0 || this.X > 290) {
            throw new Error("蛇撞墙了")
        }
        this.moveBody()
        this.head.style.left = value + 'px'
    }

    set Y(value){
        if(this.Y === value) {
            return
        }
        if(this.Y < 0 || this.Y > 290) {
            throw new Error("蛇撞墙了")
        }
        this.moveBody()
        this.head.style.top = value + 'px'
    }

    addBody() {
        this.element.insertAdjacentHTML("beforeend", "<div></div>")
    }

    moveBody() {
        for (let i = this.snakeBody.length - 1; i > 0; i--) {
            let x = (this.snakeBody[i - 1] as HTMLElement).offsetLeft;
            let y = (this.snakeBody[i - 1] as HTMLElement).offsetTop;

            (this.snakeBody[i] as HTMLElement).style.left = x + 'px';
            (this.snakeBody[i] as HTMLElement).style.top = y + 'px';
        }
    }
}

export default Snake